define(
    [
        'require'
    ],
    function(require){
        var ConfigSysinfoController = Ember.Controller.extend({
            btntext:"禁用时间服务器",
            isDisabled:false,
            /**
             * 从服务端获取系统信息，并对模板中需要调用的数据进行设置
             * @method requireSysinfo
            */
            requireSysinfo:function(){
                var ctrl = this;
                clearInterval(this.timeInterval);
                ctrl.store.ajax("GET","system")
                .then(function(response){
                    if(response.systemInfo == null) {
                        alertTip("查询系统信息失败");
                        return;
                    }
                    ctrl.set("sysinfo", response.systemInfo);
                    ctrl.set("monitorIFS",Ember.A(response.systemInfo.network.monitorInterfaces));
                    var dnsservers = response.systemInfo.network.managerInterface.dns;
                    ctrl.set("dns",ctrl.dnsSet(dnsservers));
                    if(response.systemInfo.systemTime.status == 0) {
                        ctrl.set("btntext","启用时间服务器");
                        ctrl.set("isDisabled", true);
                        ctrl.set("timeStatus", response.systemInfo.systemTime.status);
                    }
                    ctrl.set("tempServer", response.systemInfo.systemTime.syncServer);                        
                });
                ctrl.timeMove();                                 
            }, 
            startRealTimeMode: function(){
                if(this.timeTicket){
                    return;
                }
                var interval = 3000;
                var ctrl = this;
                ctrl.timeTicket = setInterval(function(){
                    ctrl.store.ajax("GET","system")
                    .then(function(response){                        
                        ctrl.set("sysinfo", response.systemInfo);                        
                    });                   
                },interval);
            },
            stopRealTimeMode: function(){
                clearInterval(this.timeTicket);
                this.timeTicket = null;
            },
            actions:{
                closeDialog: function(){
                    var dialog = Broada.getView("config-Lic-leadIn");
                    Broada.getView("config-Lic-leadIn").closeDialog();
                },
                LicApply: function(){
                    this.set("setLicName",null);
                    this.set("serviceInputName","")
                    var dialog = Broada.getView("setLicName");
                    dialog.openDialog();
                },
                leadInDialog: function(){
                    this.set("formTip", null);
                    this.set("saveResult", null);
                    this.set("showImg",false);
                    var dialog = Broada.getView("config-Lic-leadIn");
                    Broada.getView("config-Lic-leadIn").openDialog();
                },                
                leadIn:function(){
                    var ctrl = this;
                    var dialog = Broada.getView("config-Lic-leadIn");
                    
                    if($("#FileText").val() == ""){
                        this.set("formTip", "请选择文件！");
                        return;
                    }
                    this.set("showImg",true);

                    APM.iframeCallback = function(status,num,message) {
                        if(status){
                            if(status==1){
                                alertTip("证书导入成功");
                            }
                            if(status==2){
                                alertTip('证书导入失败'+message);
                            }
                            if(status==3){
                                alertTip('导入数据为空！');
                            }
                            if(status==4){
                                alertTip('上传失败,文件应为csv格式！');
                            }
                            if(status==5){
                                alertTip('上传失败,文件尺寸过大!');
                            }
                            if(status==6){
                                alertTip('上传失败,文件格式受限制且尺寸过大!');
                            }
                            if(status==7){
                                alertTip('没有选择上传文件！');
                            }
                            if(status==8){
                                alertTip('上传失败,'+message);
                            }
                        }
                        ctrl.set("showImg",false);
                        Broada.getView("config-Lic-leadIn").closeDialog();
                        APM.iframeCallback = null;
                    };
                    
                    var form1 = $('#leadForm');
                    form1[0].method="POST";
                    form1[0].action="../front/rest/apm/nodes/licimport?token="+encodeURIComponent($.cookie("token"));
                    form1[0].submit();
                },

                /**
                 * 打开“修改主机名”界面，并将数据显示出来
                 * @method hostNameModify
                */
                hostNameModify:function(){
                    var hnModifyView = Broada.getView("configSysinfoHostNameModify");
                    this.set("hostNameMTip", null);
                    hnModifyView.openDialog();
                    var hostname = this.get("sysinfo.osInfo.hostName");
                    this.set("tempHostName",hostname);
                },
                /**
                 * 打开“修改时间”界面，并将数据显示出来
                 * @method timeModify
                */
                timeModify:function(){                   
                    var ctrl = this, tModifyView = Broada.getView("configSysinfoTimeModify");
                    this.set("timeMTip", null);
                    clearInterval(this.timeInterval);
                    tModifyView.openDialog();
                    var date = this.get("sysinfo.systemTime.time");
                    var time = APM.util.formatDate(new Date(parseInt(date)), 'HH:mm:ss');
                    var timeArr = time.split(":");
                    this.set("tempHour",timeArr[0]);
                    this.set("tempMinute",timeArr[1]);
                    this.set("tempSecond",timeArr[2]);
                },
                /**
                 * 打开“修改时间服务器”界面，并将数据显示出来
                 * @method syncServerModify
                */
                syncServerModify:function(){                    
                    var tsModifyView = Broada.getView("configSysinfoSyncServerModify");
                    this.set("syncServerMTip", null);                    
                    tsModifyView.openDialog();
                    var syncServer = this.get("sysinfo.systemTime.syncServer");
                    this.set("syncServer",syncServer);
                },
                /**
                 * 打开“修改管理接口”界面，并将数据显示出来
                 * @method ManagementInterfaceModify
                */
                ManagementInterfaceModify:function(){                    
                    var mIModifyView = Broada.getView("configSysinfoMIModify");                    
                    var dnsservers = this.get("sysinfo.network.managerInterface.dns");
                    this.set("dns",this.dnsSet(dnsservers));
                    this.set("MIMTip", null);
                    mIModifyView.openDialog();
                    var managerInterface = this.get("sysinfo.network.managerInterface");
                    this.set("tempIp", managerInterface.ip);
                    this.set("tempNetmask", managerInterface.netmask);
                    this.set("tempGateway", managerInterface.gateway);
                },
                /**
                 * “禁止或开启时间服务器”按钮的操作，并将相应的状态传给服务器
                 * @method tsChosen
                */
                tsChosen:function(){ 
                    var ctrl = this;                  
                    if(ctrl.isDisabled==true){
                        ctrl.set("isDisabled",false);
                        ctrl.store.ajax("PUT", "system/time/status", {status: 1})
                        .then(function(){
                            ctrl.set("timeStatus", 1);
                        });
                    }else{
                        ctrl.set("isDisabled",true);
                        ctrl.store.ajax("PUT", "system/time/status", {status: 0})
                        .then(function(){
                            ctrl.set("timeStatus", 0);
                        });
                    }
                    if(ctrl.btntext=="禁用时间服务器"){
                        ctrl.set("btntext","启用时间服务器");                        
                    }else{
                        ctrl.set("btntext","禁用时间服务器");
                    }  
                }
            },
            dialogButtons: {
                /**
                 * 修改界面中，点击确定按钮时，对修改的数据进行验证，
                 * 若验证成功则上传数据，关闭窗口；否则停在该页面
                 * @method ok
                */
                ok: {
                    text: "确定",
                    "class": "btn btn-primary",
                    click: function() {
                        var ctrl = this.get("controller"); 
                        switch(this.id){
                            case "configSysinfoHostNameModify":
                                ctrl.updateHostName();
                                break;
                            case "configSysinfoTimeModify":
                                ctrl.updateTime();                               
                                ctrl.timeMove();
                                break;
                            case "configSysinfoSyncServerModify":
                                ctrl.updateSyncServer();
                                break;
                            case "configSysinfoMIModify":
                                ctrl.updateMIM();
                                break;
                            default:
                                if(!ctrl.get("serviceInputName")){
                                    ctrl.set("setLicName","客户名称不允许为空");
                                    //ctrl.set("formTip","客户名称不能为空!");
                                    break;
                                }
                                var url="/front/rest/apm/nodes/licreq?consumer="+ctrl.get("serviceInputName"),
                                    dialog = Broada.getView("setLicName");
                                window.location.href =url;
                              
                                dialog.closeDialog();
                        }
                    }
                },
                /**
                 * 修改界面中，点击取消按钮时，关闭相应的窗口
                 * @method cancel
                */
                cancel: {
                    text: "取消",
                    "class": "btn",
                    click: function() {
                        this.closeDialog();
                    }
                }
            },
            /**
             * 上传更新主机名，并在主界面中给出提示
             * @method updateHostName
            */
            updateHostName:function(){
                var ctrl = this,
                    hostName = this.get("tempHostName");
                if( !this.validateHostNameM()){
                    return;
                }else{
                    Broada.getView("configSysinfoHostNameModify").closeDialog();
                }
                ctrl.store.ajax("PUT", "system/os/hostname", {hostName: hostName})
                .then(function(){
                    alertTip("主机名已修改为 "+ hostName);
                });
            },
            /**
             * 上传更新时间，并在主界面中给出提示
             * @method updateTime
            */
            updateTime:function(){
                var ctrl = this;
                var tempdate = "";
                var timeArr = [this.get("tempHour"),this.get("tempMinute"),this.get("tempSecond")];
                var date = new Date(parseInt(this.get("sysinfo.systemTime.time")));
                date.setHours(parseInt(timeArr[0]));
                date.setMinutes(parseInt(timeArr[1]));
                date.setSeconds(parseInt(timeArr[2]));
                tempdate =  Date.parse(date);
                if( !this.validateTimeM(timeArr)){
                    return;
                }else{
                    Broada.getView("configSysinfoTimeModify").closeDialog();
                }
                this.set('sysinfo.systemTime.time', date.getTime());
                ctrl.store.ajax("PUT", "system/time", {date: tempdate})
                .then(function(){
                    alertTip("时间已修改为 "+ timeArr[0]+":"+timeArr[1]+":"+timeArr[2]);
                });
            },
            /**
             * 上传更新时间服务器，并在主界面中给出提示
             * @method updateSyncServer
            */
            updateSyncServer:function(){
                var ctrl = this,
                    tempServer = this.get("tempServer");
                if( !this.validateSyncServerM() ){
                    return;
                }else{
                    Broada.getView("configSysinfoSyncServerModify").closeDialog();
                }
                var status = this.get("sysinfo.systemTime.status");
                ctrl.store.ajax("PUT", "system/time/sync", {status : status, syncServer: tempServer})
                .then(function(){
                    alertTip("时间服务器已修改为 "+ tempServer);
                });
            },
            /**
             * 上传更新管理接口的信息，并在主界面中给出提示
             * @method updateMIM
            */
            updateMIM:function(){
                var ctrl = this,
                    tempName = this.get("sysinfo.network.managerInterface.name"),
                    tempIp = this.get("tempIp"),
                    tempNetmask = this.get("tempNetmask"),
                    tempGateway = this.get("tempGateway"),
                    tempDNSObj = this.get("dns"),
                    tempArr = [],
                    tempDNS = "";
                for(var i=0; i<tempDNSObj.length;i++){
                    tempArr.push(tempDNSObj[i].value);
                }
                tempDNS = tempArr.join(", ");
                if( !this.validateMIM() ){
                    return;
                }else{
                    Broada.getView("configSysinfoMIModify").closeDialog();
                }
                ctrl.store.ajax("PUT", "system/network", 
                    {name:tempName,ip:tempIp,netmask:tempNetmask,gateway:tempGateway,dns:tempDNS})
                .then(function(){
                    alertTip("地址已修改为 "+ tempIp+";<br>掩码已修改为"+tempNetmask+";<br>网关已修改为"+tempGateway+";<br>DNS服务器已修改为"+tempDNS);
                });
            },
            /**
             * 验证主机名，失败时给出提示
             * @method validateHostNameM
             * @return {true} 验证成功
             *         {false} 验证失败
            */
            validateHostNameM:function(){
                var hostNameInput = this.get("tempHostName");
                var reg=/^[a-zA-Z0-9_.]{1,}$/;
                if (!reg.test(hostNameInput)) {
                    this.set("hostNameMTip", "主机名为空或格式不对，请输入英文，数字，点或下划线"); 
                    return false;                      
                }else{
                    this.set("hostNameMTip", null);
                    this.set("sysinfo.osInfo.hostName",hostNameInput);
                    return true;
                }                
            },
            /**
             * 验证时间，失败时给出提示
             * @method validateTimeM
             * @return {true} 验证成功
             *         {false} 验证失败
            */
            validateTimeM:function(currentTime){  
                var tempTimeArr = ["小时","分钟","秒钟"];
                var tipTimeArr = [];//提示用的数组
                var timeTipContent = "";
                var time = [];//验证后的时间
                var doubleNum = /^\d{2}$/;
                if(parseInt(currentTime[0])>=0 && parseInt(currentTime[0])<24 && currentTime[0]!="" && doubleNum.test(currentTime[0])){
                    time.push(currentTime[0]);                    
                }else{
                    tipTimeArr.push(tempTimeArr[0]);
                }
                for(var i=1; i<currentTime.length; i++){ 
                    if(parseInt(currentTime[i])>=0 && parseInt(currentTime[i])<60 && currentTime[i]!="" && doubleNum.test(currentTime[i])){                        
                        time.push(currentTime[i]);
                    }else{
                        tipTimeArr.push(tempTimeArr[i]);
                    }                   
                }
                if(tipTimeArr.length!=0){
                    timeTipContent = tipTimeArr.join(",")+"输入为空或格式不对，请重新输入！";
                    this.set("timeMTip", timeTipContent);
                    return false;
                }else{
                    this.set("timeMTip", null);
                    return true;
                }          
            },
            /**
             * 验证时间服务器，失败时给出提示
             * @method validateSyncServerM
             * @return {true} 验证成功
             *         {false} 验证失败
            */
            validateSyncServerM:function(){
                var syncServerInput = this.get("tempServer");
                var reg=/^[a-zA-Z0-9_.]{1,}$/;
                if (!reg.test(syncServerInput)) {
                    this.set("syncServerMTip", "服务器为空或格式不对，请输入IP或域名"); 
                    return false;                      
                }else{
                    this.set("syncServerMTip", null);
                    return true;
                }
            },
            /**
             * 验证管理接口信息，失败时给出提示
             * @method validateMIM
             * @return {true} 验证成功
             *         {false} 验证失败
            */
            validateMIM:function(){ 
                var tempMIArr = ["地址","掩码","网关","DNS服务器"]; 
                var tipMIArr = [];//格式不对的input对应的名称
                var tipNullArr = [];//内容为空的input对应的名称
                var mITipContent = "";
                var tempDNS = [];
                var dnsArr = []
                for(var i=0; i<this.get("dns").length;i++){
                    dnsArr.push(this.get("dns")[i].value);
                }
                var miInput = [this.get("tempIp"),this.get("tempNetmask"),this.get("tempGateway")];
                var reg=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
                for(var i=0; i<miInput.length; i++){
                    if(miInput[i] == ""){
                        tipNullArr.push(tempMIArr[i]);
                    }
                    else if(!reg.test(miInput[i])) {
                        tipMIArr.push(tempMIArr[i]);                      
                    }
                }
                for(var i=0; i<dnsArr.length; i++){
                    if(dnsArr[i] == ""){
                        continue;
                    }
                    else if(!reg.test(dnsArr[i])) {
                        tipMIArr.push(tempMIArr[3]); 
                        continue;                     
                    }
                }                
                if((tipNullArr.length!=0) || (tipMIArr.length!=0)){
                    if(tipNullArr.length!=0){
                        mITipContent = tipNullArr.join(",")+"为空;";
                    }
                    if(tipMIArr.length!=0){
                        mITipContent += tipMIArr.join(",")+"格式非法，请重新输入!"
                    }                    
                    this.set("MIMTip", mITipContent);
                    return false;
                }else{
                    this.set("MIMTip", null);
                    this.set("sysinfo.network.managerInterface.ip", miInput[0]);
                    this.set("sysinfo.network.managerInterface.netmask", miInput[1]);
                    this.set("sysinfo.network.managerInterface.gateway", miInput[2]);
                    for(var j=0; j<dnsArr.length; j++){
                        tempDNS.push(dnsArr[j]);
                    }
                    this.set("sysinfo.network.managerInterface.dns", tempDNS);
                    return true;
                }                
            },
            timeMove:function(){
                var ctrl = this;
                ctrl.timeInterval = setInterval(function(){
                    var time = parseInt(ctrl.get('sysinfo.systemTime.time'));
                    ctrl.set('sysinfo.systemTime.time', time+1000);
                }, 1000);
            },
            /**
             * 将服务端获取的dns转换两个obj形式的Ember数组
             * @arguments {dnsservers} 服务端数据，字符串形式
             * @method dnsSet
             * @return {Ember.A(dnsObj)} 返回的数据
            */
            dnsSet:function(dnsservers){
                var dnsArr = dnsservers.split(",");
                var dnsObj =[];
                for(var i=0; i<dnsArr.length; i++){
                    var tempdnsobj = {};
                    tempdnsobj.value = dnsArr[i].trim();
                    dnsObj.push(tempdnsobj);
                }
                if(dnsObj.length<2){
                    var dnsNull = {};
                    dnsNull.value = "";
                    dnsObj.push(dnsNull);
                }
                return Ember.A(dnsObj);
            }

        });
        APM.ConfigSysinfoController = ConfigSysinfoController;
        return ConfigSysinfoController;
    }
);